/*
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
*/
package org.xptracker.web;

import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.SimpleError;
import org.xptracker.domain.WikiPage;
import org.xptracker.persistence.PersistenceManager;
import org.xptracker.wiki.WikiWordWidget;

import javax.servlet.http.HttpSession;

@UrlBinding("/Wiki.action")
public class WikiActionBean extends StandardActionBean {
  private static final String DEFAULT_PAGE = "FrontPage";

  private WikiPage page;

  private String name = DEFAULT_PAGE;
  private Integer depth;

  public WikiPage getPage() {
    return page;
  }

  public void setPage(WikiPage page) {
    this.page = page;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public Integer getDepth() {
    return depth;
  }

  public void setDepth(Integer depth) {
    this.depth = depth;
  }

  @DefaultHandler
  public Resolution display() {
    if (page == null) {
      return new RedirectResolution(MainActionBean.class).flash(this);
    }
    getHistory().push(name);
    return new ForwardResolution("/wiki/display.jsp");
  }

  private boolean isValidName() {
    return name != null && WikiWordWidget.WIKI_WORD_PATTERN.matcher(name).matches();
  }

  public Resolution edit() {
    return new ForwardResolution("/wiki/edit.jsp");
  }

  @After(stages = LifecycleStage.BindingAndValidation, on = {"edit", "display"})
  private void loadPage() {
    if (isValidName()) {
      page = persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<WikiPage>() {
        public WikiPage doUpdate(PersistenceManager.UpdateReceiver receiver) {
          return domain.loadWikiPage(receiver, name);
        }
      });
    }
  }

  @After(stages = LifecycleStage.BindingAndValidation)
  public void fixHistory() {
    if (depth != null) {
      getHistory().rollback(depth);
    }
  }

  public History getHistory() {
    return getHistory(getContext().getRequest().getSession());
  }

  public static History getHistory(HttpSession session) {
    History h = (History) session.getAttribute("history");
    if (h == null) {
      h = new History();
      session.setAttribute("history", h);
    }
    return h;
  }

  @Before(stages = LifecycleStage.BindingAndValidation, on = "save")
  public void setupBinding() {
    name = param("name");
    loadPage();
  }

  public Resolution save() {
    if (page == null) {
      getContext().getValidationErrors().add("name", new SimpleError("''{1}'' is not a WikiWord", name));
      name = DEFAULT_PAGE;
      loadPage();
    } else {
      final String content = page.getContent().getContent();
      page = persistenceManager.inTransaction(new PersistenceManager.UpdateHandler<WikiPage>() {
        public WikiPage doUpdate(PersistenceManager.UpdateReceiver receiver) {
          final WikiPage page = domain.loadWikiPage(receiver, name);
          page.getContent().setContent(content);
          receiver.update(page);
          return page;
        }
      });
    }

    return new RedirectResolution(WikiActionBean.class).addParameter("name", name);
  }
}
